<template>
  <el-drawer :title="title" :visible.sync="openDialog" size="70%" @closed="handleClose" :destroy-on-close="true" :wrapperClosable="false">
    <el-card class="box-card">
      <div slot="header" class="clearfix flex-hs">
        <span>项目名称：{{pro_name}}</span>

      </div>
      <el-table :data="proInfo">
        <el-table-column prop="name" label="房间名称">
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.name" size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="ps" label="面积/m^2" width="200">
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.ps" size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="pc" label="周长/m" width="200">
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.pc" size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini"  type="primary" icon="el-icon-edit" v-if="scope.row.id" 
             :disabled="!(scope.row.ps&&scope.row.pc&&scope.row.name)"
              @click="addnewspace(scope.row)"></el-button>
            <el-button size="mini"  type="success" icon="el-icon-circle-plus-outline" v-else
              :disabled="!(scope.row.ps&&scope.row.pc&&scope.row.name)"
              @click="addnewspace(scope.row)">
            </el-button>
            <el-popconfirm title="确定删除吗？" @onConfirm="delspeace(scope.row)" v-if="scope.row.id">
              <el-button size="mini" slot="reference" type="danger" icon="el-icon-delete"></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="flex-hb">
        <span>基础图纸信息</span>
        <el-button size="mini" @click="sendState"  type="primary" icon="el-icon-s-promotion" :disabled="show_state==1">{{show_state==1?'已发送':'发送'}}</el-button>
      </div>
      <el-table :data="pictureInfo">
        <el-table-column prop="name" label="图纸名称" width="200">
          <!-- <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.name" size="mini"></el-input>
          </template> -->
        </el-table-column>
        <el-table-column prop="gs" label="格式" width="200">
          <!-- <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.square" size="mini"></el-input>
          </template> -->
        </el-table-column>
        <el-table-column prop="girth" label="附件" >
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.path" size="mini" v-if="scope.row.gs=='链接'"></el-input>
            <other-upload  v-model="scope.row.path" :width='74' :height="74" v-else/>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button size="mini"  type="danger" icon="el-icon-download" v-if="scope.row.gs=='DWG'" @click="downLoad(scope.row.path)">下载文件</el-button>
            <vue-qr :logoSrc="imagePath" :downloadButton="true" v-else :text="scope.row.path" colorDark="green" :size="100"></vue-qr>
          </template>
        </el-table-column>
      </el-table>
      <div style="padding:10px 0">
        <el-button type="primary" @click="saveBasePic()" size="mini">保存基础图纸</el-button>
      </div>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix flex-hs">
        <span>其他图纸信息</span>
      </div>
      <el-table :data="otherPicList">
        <el-table-column prop="name" label="图纸名称" width="200">
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.name" size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="gs" label="文件" width="200">
          <template slot-scope="scope">
            <pt-upload  v-model="scope.row.path" :width='74' :height="74" :tip="false"></pt-upload>
          </template>
        </el-table-column>
        <el-table-column label="备注" >
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.mark" size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button size="mini"  type="danger" icon="el-icon-download" v-if="scope.row.path" @click="downLoad(scope.row.name,scope.row.path)"></el-button>
            <el-button size="mini"  type="success" icon="el-icon-circle-plus-outline" 
              :disabled="!(scope.row.path&&scope.row.name&&scope.row.mark)"
             @click="addnewPic"></el-button>
            <el-popconfirm title="确定删除吗？" @onConfirm="delOtherImg(scope.$index)">
              <el-button size="mini" slot="reference" type="danger" icon="el-icon-delete"></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="padding:10px 0">
        <el-button type="primary" @click="saveOtherPic" size="mini">保存施工图纸</el-button>
      </div>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>拆单信息</span>
      </div>
      <el-collapse v-model="activeName" >
        <el-collapse-item :name="i" v-for="(item, i) in cateData" :key="i">
          <template slot="title">
            <span style="color:#FF9355;font-size:18px">{{ item.name }}</span><i class="header-icon el-icon-s-unfold"></i>
          </template>
          <div style="padding-left:30px">
            <el-collapse v-model="activeName2" >
              <el-collapse-item :name="j" v-for="(e, j) in item.children" :key="j">
                <template slot="title">
                  <span style="color:#E3C608;font-size:16px;font-wight:700">{{ e.name }}（{{e.products.length-1}}）</span><i class="header-icon el-icon-wind-power"></i>
                </template>
                <!-- <div style="padding:10px 0">
                  <el-button type="primary" @click="addgoods(e.products)" size="mini">添加商品</el-button>
                </div> -->
                <el-table :data="e.products">
                  <el-table-column label="商品名称">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.pname" size="mini" filterable remote placeholder="请输入商品关键词" :remote-method="remoteMethod" :loading="searchloading" @change="chcekedChange(scope.row)" @focus="getalldata(e.id)">
                        <el-option v-for="item in goodsoptions" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="规格">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.ggObj.name" size="mini" placeholder="请选择商品后再选规格" :disabled="!scope.row.pro_change">
                        <el-option v-for="item in ggoptions" :key="item.id" :label="item.name + '￥' + item.price" :value="item.id"> </el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="数量" width="100">
                    <template slot-scope="scope">
                      <el-input type="text" v-model="scope.row.num" size="mini"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="px" label="排序编号" width="100">
                    <template slot-scope="scope">
                      <el-input type="text" v-model="scope.row.px" size="mini"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" width="200">
                    <template slot-scope="scope">
                      <el-input type="textarea" :autosize="true" v-model="scope.row.desc" size="mini"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="200">
                    <template slot-scope="scope">
                      <el-button size="mini"  type="primary" icon="el-icon-edit" v-if="scope.row.id"
                        :disabled="!(scope.row.pname&&scope.row.ggObj.name&&scope.row.num)"
                       @click="addAndSaveGoods(scope.row)"></el-button>
                      <el-button size="mini"  type="success" icon="el-icon-circle-plus-outline" v-else
                        :disabled="!(scope.row.pname&&scope.row.ggObj.name&&scope.row.num)"
                        @click="addAndSaveGoods(scope.row)">
                      </el-button>
                      <el-popconfirm title="确定删除吗？" v-if="scope.row.id"  @onConfirm="delgoods(e.products,scope.row, scope.$index)">
                        <el-button size="mini" slot="reference" type="danger" icon="el-icon-delete"></el-button>
                      </el-popconfirm>
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <div class="drawer-footer">
      <el-button type="primary" @click="handleClose">返 回</el-button>
    </div>
    <check-goods v-if="openCheckGoods" ref="refCheckGoods" @hasChecked="CheckedList" />
  </el-drawer>
</template>

<script>
import { mapState } from 'vuex'
import otherUpload from '../imageUpload/otherUpload'
import VueQr from 'vue-qr'
export default {
  components: {
    otherUpload,
    VueQr
  },
  data() {
    return {
      proChange:true,
      pro_name:'',
      imagePath: require('../../assets/logo.png'),//中间logo的地址
      activeName: '1',
      activeName2: '1',
      id: '',
      show_state:2,
      openid: '',
      project_id:'',
      proName: '',
      title: '新增角色信息',
      openDialog: false,
      openCheckGoods: false,
      loading: false,
      searchloading: false,
      proInfo: [],
      basePicObj:{
        liangfang:'',
        draw_dwg:'',
        xiaoguotu:'',
        power_draw:''
      },
      draw_imgList:[],
      pictureInfo:[
        { name: '量房图', gs: "DWG",fileName: 'liangfang', path: '123456' },
        { name: '施工图纸源文件', gs: "DWG",fileName: 'draw_dwg',  path: '456789' },
        { name: '效果图', gs: "链接", fileName: 'xiaoguotu',path: '' },
        { name: '水电施工图', gs: "链接",fileName: 'power_draw', path: '' },
      ],
      otherPicList:[
        {name:'图纸1',path:'',mark:''}
      ],
      cateData: [],
      goodsoptions: [],
      ggoptions: [],
      moreproInfo: {
        id:'',
        num:'',
        pname:'',
        ggObj:{},
        px:'',
        desc:'备注'
      }
    }
  },
  computed: {
    ...mapState(['$roleOption', '$stateOption', '$role', '$state']),
    queryData() {
      return {
        proName: this.proName,
        proInfo: JSON.stringify(this.proInfo),
        splitData: JSON.stringify(this.cateData),
        openid: this.openid
      }
    }
  },
  methods: {
    init(val, cateData) {
      console.log(cateData,456);
      this.pro_name =val.name +'-'+ val.province+val.city+val.town+val.detail
      this.activeName = '1'
      this.activeName2 = '1'
      this.openid = val.openid
      this.project_id = val.id
      this.cateData = cateData
      this.getSpaceList()//空间数据
      this.getNowProData()//图纸数据
      this.getSplitData() //商品数据
      this.openDialog = true
      if (val) {
        this.title = '拆单信息'
      } else {
        this.title = '新建拆单'
      }
    },
    //文件下载
    downLoad(name,path) {
      const a = document.createElement('a')
      a.download = name + '.'+ path.replace(/.+\./,"");
      a.href = this.$http.staticURL + path  // "/uploads/upload/b9/ca677a2c96cd96f7a3eb703e3f2bd5.png"
      // let bloburl = new Blob(fileurl);// 字符内容转变成blob地址
      // a.href = URL.createObjectURL(bloburl);
      document.body.appendChild(a);                   
      a.click();// 触发点击
      a.style.display = 'none';
      document.body.removeChild(a); // 然后移除
    },
    // 保存基础图纸
    saveBasePic(){
      this.$showLoading()
      let obj = {
        id:this.project_id,
        openid:this.openid,
      }
      this.pictureInfo.forEach(e=>{
        obj[e.fileName] = e.path
      })
      this.basePicObj = obj
      console.log(this.basePicObj,222);
      this.addAndSaveChaiDan(obj)
    },
    // 修改发送状态,点击发送
    sendState() {
        this.$confirm('此操作将发送图纸文件按至客户端, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           let obj = {
            id:this.project_id,
            openid:this.openid,
            show_state:1
          }
          this.addAndSaveChaiDan(obj)
          this.$message({
            type: 'success',
            message: '已成功发送!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消发送'
          });          
        });
    },
    //保存其他图纸
    saveOtherPic() {
      console.log(this.otherPicList)
      let isempty = this.otherPicList.some(e=>e.name==''||e.path==''||e.mark=='')
      if(isempty) return this.$message.error('请填写完整信息后保存！')
      let obj = {
        id:this.project_id,
        openid:this.openid,
        draw_img:JSON.stringify(this.otherPicList)
      }
      this.addAndSaveChaiDan(obj)
    },
    delOtherImg(index){
      let list = JSON.parse(JSON.stringify(this.otherPicList))
      list.splice(index, 1)
      this.otherPicList = list
      // this.saveOtherPic()
    },
    // 拆单项目修改新增图纸,发送状态等 通用接口
    addAndSaveChaiDan(obj){
      this.$http.httpPost('/User/splitUpdate',obj).then(res=>{
        console.log(res,'xiuga')
        if(res.data.code==0){
          this.getNowProData()
        }else{
          if(res.data.msg){
            this.$message.error(res.data.msg)
          }
        }
      })
    },
    addnewPic(){
      let newRow = {name:'新建图纸',path:'',mark:''}
      let arrsplist = JSON.parse(JSON.stringify(this.otherPicList))
      arrsplist.push(newRow)
      this.otherPicList = arrsplist
    },
  
    addnewspace(obj) {
      const {id,name,ps,pc } = obj
      let addData = {
        id,
        name,
        ps,
        pc,
        openid: this.openid,
        project_id:this.project_id      
      }
      this.addAndupdateNewSpace(addData)
    },
    //新增空间
    addAndupdateNewSpace(obj) {
      this.$http.httpPost('/SplitOrder/splitInfoSave',obj).then(res=>{
        console.log(res,'新增')
        if(res.data.code == 0){
          this.$message.success('添加/修改成功！')
          this.getSpaceList()
        }
      })
    },
    // 查询拆单信息
    getSplitData() {
      this.$http.httpPost('/SplitOrder/splitList',{openid:this.openid,project_id:this.project_id }).then(res=>{
        console.log(res,'新增')
        if(res.data.code == 0){
          let splitGoods =  res.data.data
          
          if(splitGoods&&splitGoods.length>0){
            splitGoods.forEach(m=>{
              m.products.forEach(n=>{
                let ggarr = JSON.parse(n.specification)
                let resobj = ggarr.filter(a=>a.id==n.spec_id)
                n.ggObj = resobj.length>0?resobj[0]:ggarr[0]
              })
            })
            console.log(splitGoods,789789); 
            this.cateData.forEach(cate1=>{
              cate1.children.forEach(item=>{
                let proArr = splitGoods.filter(pro=>pro.name==item.name)
                if ( proArr.length>0 && proArr[0].products) {          
                  item.products = proArr[0].products
                  item.products.push(JSON.parse(JSON.stringify(this.moreproInfo)))
                } else{
                  item.products = [JSON.parse(JSON.stringify(this.moreproInfo))]
                }
              })
            })
          }
        }else{
          this.$message.error('网络异常！')
        }
      })
    },
    // 查询该项目数据图纸数据
    getNowProData() {
       this.$http.httpPost('/user/addressInfoList',{openid:this.openid,project_id:this.project_id }).then(res=>{
        console.log(res)
        if(res.data.code == 0){
          // 发送状态
          if(res.data.data.data &&res.data.data.data.length>0){
            let proData = res.data.data.data[0]
            this.show_state = proData.show_state
            this.basePicObj= {
              liangfang: proData.liangfang,
              draw_dwg: proData.draw_dwg,
              xiaoguotu: proData.xiaoguotu,
              power_draw: proData.power_draw
            }
            this.otherPicList = JSON.parse(proData.draw_img)?JSON.parse(proData.draw_img):[]
            if(this.otherPicList.length == 0){
              this.otherPicList.push({name:'新建图纸',path:'',mark:''})
            }
            this.pictureInfo.forEach(e=>{
              if(e.fileName == 'liangfang'){
                e.path = proData.liangfang
              }
              if(e.fileName == 'draw_dwg'){
                e.path = proData.draw_dwg
              }
              if(e.fileName == 'xiaoguotu'){
                e.path = proData.xiaoguotu
              }
              if(e.fileName == 'power_draw'){
                e.path = proData.power_draw
              }
            })
            this.$showLoading('close')
           
          }
        }
      })
    },
    // 查询空间列表
    getSpaceList(){
       this.$http.httpPost('/SplitOrder/splitInfoList',{openid:this.openid,project_id:this.project_id }).then(res=>{
        console.log(res)
        if(res.data.code == 0){
          this.proInfo = res.data.data
          this.proInfo.push({id:'',name:"新空间",ps:'',pc:''})
        }
      })
    },
    // 新增拆单商品
    addAndSaveGoods(row) {
      console.log(row,789);
      let obj= {
        id:row.id,
        product_id:row.pro_change? row.pname:row.product_id,
        spec_id:row.pro_change?row.ggObj.name: row.spec_id,
        num:row.num,
        desc:row.desc,
        project_id:this.project_id,
        openid:this.openid
      }
      this.addSplitGoods(obj)
    },
  
    addSplitGoods(obj) {
      this.$showLoading()
      this.$http.httpPost('/SplitOrder/save',obj).then(res=>{
        console.log(res)
        if(res.data.code == 0){
          this.$showLoading('close')
          this.getSplitData()
          this.$operateTip()
        }else{
          this.$message.error('操作失败!')
        }
      })
    },
    remoteMethod(query) {
      this.searchloading = true
      this.getdoodsData(this.cate2, query)
    },
    getalldata(cate2) {
      this.cate2 = cate2
      this.searchloading = true
      this.getdoodsData(this.cate2, '')
    },
    chcekedChange(row) {
      console.log(row, '选择我了')
      row.pro_change = true
      row.ggObj.name? row.ggObj.name = '':''
      
    
      this.moreproInfo.ggObj = {}
      this.$http.httpPost('/products/productsList', { id: row.pname }).then(res => {
        if (res.data.code === 0&&res.data.data.data.length>0) {

          this.ggoptions = JSON.parse(res.data.data.data[0].specification)
          this.proChange = false

        }
      })
    },
    delspeace(row) {
      let obj = {
        id:row.id,
        openid:this.openid,
        project_id:row.project_id
      }
      this.$http.httpPost('/SplitOrder/delInfo', obj).then(res => {
        if (res.data.code === 0) {
          this.$message.success('删除成功！')
          this.getSpaceList()
        }
      })
      
    },
    delgoods(list,item,index){
      let obj = {
        id:item.id,
        openid:this.openid,
        project_id:item.project_id
      }
      this.$http.httpPost('/SplitOrder/delList', obj).then(res => {
        if (res.data.code === 0) {
          this.$message.success('删除成功！')
          this.getSplitData()
        }
      })

      // console.log(item,789);
      
      // list.splice(index, 1)
    },
    getdoodsData(cate2, name) {
      this.$http.httpPost('/products/productsList', { cate2: cate2, count: 9999, page: 1, keyword: name, state: 1 }).then(res => {
        if (res.data.code === 0) {
          // this.total = res.data.data.total
          this.goodsoptions = res.data.data.data
          this.searchloading = false
        }
      })
    },
    CheckedList(val, list) {
      console.log(val, '拿到数据')
    },
    handleClose(done) {
      this.openDialog = false
      this.$emit('save')
    }
    
  }
}
</script>
<style lang="less" scoped></style>
